package cake.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class UploadPicture {
	
	public static List<String> upload(HttpServletRequest request,String savePath) {
		try {
			List<String> files=new ArrayList<String>();
			
			String tmpPath = "c:\\tmpdir";
			//String savePath=request.getSession().getServletContext().getRealPath("/")+"image\\temp\\";
			File tmpDir = new File(tmpPath);
			File saveDir = new File(savePath);
			if (!tmpDir.isDirectory())
				tmpDir.mkdir();
			if (!saveDir.isDirectory())
				if(saveDir.mkdirs()){
					System.out.println(saveDir+" has been created");
				}

			if (ServletFileUpload.isMultipartContent(request)) {
				DiskFileItemFactory dff = new DiskFileItemFactory();
				dff.setRepository(tmpDir);
				dff.setSizeThreshold(1024000);
				ServletFileUpload sfu = new ServletFileUpload(dff);
				sfu.setFileSizeMax(1024*1024*2);
				sfu.setSizeMax(1024*1024*2*5);
				FileItemIterator fii = sfu.getItemIterator(request);
				while (fii.hasNext()) {
					FileItemStream fis = fii.next();
					if (!fis.isFormField() && fis.getName().length() > 0) {
						String fileName = fis.getName().substring(
								fis.getName().lastIndexOf("\\")+1);
						
						SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddhhmmssSSS");
						String datetime = tempDate.format(new Date());
						
						fileName=datetime+fileName.substring(fileName.lastIndexOf("."));
						BufferedInputStream in = new BufferedInputStream(fis.openStream());
						
						File destFile=new File(savePath+ fileName);
						if(destFile.exists()){
							fileName="sec_"+fileName;
						}
						BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
						Streams.copy(in, out, true);
						
						
//						String fromFileStr=savePath+ fileName;
//						String saveToFileStr=savePath+ "suoluetu_" +fileName;
//						int width=150;
//						int height=100;
//						if(ImageHelper.saveImageAsThumbnail(fromFileStr, saveToFileStr, width, height)){
//							
//						}
						files.add(savePath + fileName);
					}
				}
				return files;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}
}
